/**
 * 将一维数组转成树
 * @param {Array} menuList
 * @param {Number} parentId
 */
export const covertToTree = (menuList, parentId) => {
  const tree = []

  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].parentId === parentId) {
      const children = covertToTree(menuList, menuList[i].menuId)

      if (children.length) {
        menuList[i].children = children
      }

      tree.push(menuList[i])
    }
  }

  return tree
}

const findBtnPermissions = (list) => {
  return list.map(p => p.buttonCode)
}

/**
 * 将菜单List转成菜单树
 */
export const transformTreeAndSetProps = (menuList, parentId) => {
  let tree = []

  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].parentId === parentId) {
      let children = transformTreeAndSetProps(menuList, menuList[i].menuId)

      let hidden = menuList[i].hidden

      if (hidden === undefined || hidden === null) {
        hidden = false
      } else {
        hidden = hidden === 1 ? false : true
      }

      let item = Object.assign({}, menuList[i], {
        meta: {
          title: menuList[i].menuName,
          icon: menuList[i].icon,
          hidden
        }
      })


      // 目录或者菜单才需要添加子集，如果是按钮直接去掉children字段
      if ((item.menuType === 1 || item.menuType === 2) && children.length) {
        item.children = children
      }

      if (item.menuType === 2) {
        if (children.length) {
          // 拿到菜单里面的按钮权限
          item.meta.btnPermissions = findBtnPermissions(children)
        }

        // 外部链接
        if (item.isHref === 1) {
          item.meta.href = item.href
          item.meta.isHref = Boolean(item.isHref)
        }

        // 是否使用 keep-alive缓存组件
        item.meta.isCache = Boolean(item.isCache)
      }


      delete item.hidden
      delete item.icon
      delete item.updateId
      delete item.menuOrder
      delete item.parentIds
      delete item.menuName
      delete item.isHref
      delete item.href
      delete item.isCache

      // delete item.menuId
      delete item.parentId

      if (item.menuType !== 4) {
        delete item.buttonCode
        delete item.buttonName
      }

      if (item.menuType === 1) {
        delete item.name
      }

      if (item.menuType === 2) {
        delete item.children
      }
      // delete item.menuType

      tree.push(item)
    }
  }

  return tree
}